/************************************************************************
* path.c
* Copyright (C) Lisa Milne 2013 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "dish.h"
#include "env.h"
#include "path.h"

#include <dirent.h>

char* default_paths[] = {
	"/usr/local/bin",
	"/usr/bin",
	"/bin",
	NULL
};

char** path = NULL;

/* update the path from environment */
void epath_update()
{
	char* p = env_get("PATH");
	if (!p)
		return;

	if (path)
		clist_free(path);

	path = clist_split(p,":");
}

/* the which command put into a function */
char* epath_which(char* file)
{
	static char buff[1024];
	char** up;
	int i;

	if (!file || !file[0])
		return NULL;
	if (strchr(file,'/')) {
		strcpy(buff,file);
		if (is_exec(buff))
			return buff;
		return NULL;
	}

	if (!path)
		epath_update();
	if (!path) {
		up = default_paths;
	}else{
		up = path;
	}

	for (i=0; up[i]; i++) {
		snprintf(buff,1024,"%s/%s",up[i],file);
		if (is_exec(buff))
			return buff;
	}

	return NULL;
}

static char* fpath_search(char* dir, char* file, int e, int *c)
{
	static char buff[1024];
	DIR *d;
	struct dirent *dr;
	int l;

	d = opendir(dir);
	if (!d)
		return NULL;

	l = strlen(file);

	while ((dr = readdir(d))) {
		if (strncmp(dr->d_name,file,l))
			continue;
		if (*c) {
			(*c)--;
			continue;
		}
		snprintf(buff,1024,"%s/%s",dir,dr->d_name);
		if ((e && is_exec(buff)) || (!e && is_something(buff))) {
			if (is_dir(buff))
				strcat(buff,"/");
			closedir(d);
			return buff;
		}
	}

	closedir(d);

	return NULL;
}

/* complete the path */
char* fpath_complete(char* file, int e, int c)
{
	static char buff[1024];
	char** up;
	char* f;
	int i;

	if (!file || !file[0])
		return NULL;
	if (!e || strchr(file,'/')) {
		strcpy(buff,file);
		if (is_exec(buff))
			return buff;
		strncpy(buff,file,1024);
		f = strrchr(buff,'/');
		if (f) {
			*f = 0;
			f++;
			return fpath_search(buff,f,e,&c);
		}else{
			f = fpath_search(".",buff,e,&c);
			if (!f)
				return NULL;
			strcpy(buff,f+2);
			return buff;
		}
	}

	if (!path)
		epath_update();
	if (!path) {
		up = default_paths;
	}else{
		up = path;
	}

	for (i=0; up[i]; i++) {
		f = fpath_search(up[i],file,1,&c);
		if (f) {
			char* s = strrchr(f,'/');
			if (!s)
				return NULL;
			strcpy(buff,s+1);
			return buff;
		}
	}

	return NULL;
}
